// pub fn convert_base(num_str: &str, to_base: u32) -> String {
//     // TODO: 这里写逻辑
//     todo!()
// }


use regex::Regex;

pub fn convert_base(num_str: &str, to_base: u32) -> String {
    assert!(to_base >= 2 && to_base <= 16, "Base must be between 2 and 16");

    let re = Regex::new(r"\(([0-9]+)\)").unwrap();
    let caps = re.captures(num_str).unwrap();
    let from_base = caps[1].parse::<u32>().unwrap();

    let num_str = num_str.split("(").next().unwrap().trim();

    let mut decimal_value = 0;
    for c in num_str.chars() {
        let digit_value = match c {
            '0'..='9' => c as u32 - '0' as u32,
            'A'..='F' => c as u32 - 'A' as u32 + 10,
            'a'..='f' => c as u32 - 'a' as u32 + 10,
            _ => panic!("Invalid character in input"),
        };

        if digit_value >= from_base {
            panic!("Invalid digit for given base");
        }
        decimal_value = decimal_value * from_base + digit_value;
    }


    if decimal_value == 0 {
        return "0".to_string();
    }

    let mut result = String::new();
    while decimal_value > 0 {
        let remainder = decimal_value % to_base;
        let digit_char = if remainder < 10 {
            (remainder as u8 + '0' as u8) as char
        } else {
            (remainder as u8 - 10 + 'a' as u8) as char
        };
        result.insert(0, digit_char);
        decimal_value /= to_base;
    }
    // 输出答案
    result
    // format!("{}({})", result, to_base)
}

